package com.company.matrix;

public class ComputeArea {


    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        Rect rectA = new Rect(A, B,C,D);
        Rect rectB = new Rect(E, F,G,H);

        Rect coincidence = rectA.getCoincidence(rectB);

        return rectA.getArea()+rectB.getArea()-coincidence.getArea();
    }


    public static class Rect {
        int l, t, r, b;

        public Rect(int l, int b, int r, int t) {
            this.l = l;
            this.t = t;
            this.r = r;
            this.b = b;
        }

        public int getArea(){
            return (r-l)*(t-b);
        }

        public boolean isCoincidence(Rect other){
            // src 在 other 左侧 不相交
            if(r<=other.l)return false;
            if (l>= other.r)return false;
            if (b>=other.t)return false;
            if (t<= other.b)return false;
            return true;
        }

        public Rect getCoincidence(Rect other){
            if (!isCoincidence(other)) {
                return new Rect(0,0,0,0);
            }
            int newL= Math.max(l, other.l);
            int newT= Math.min(t, other.t);
            int newR= Math.min(r, other.r);
            int newB= Math.max(b, other.b);
            return new Rect(newL,newB,newR,newT);
        }
    }
}
